﻿using OpenNETCF.IoC;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace IoTCM
{
    public class HostModuleLoader : IModuleInfoStore
    {
        public string CatalogFilePath { get; set; }

        public Assembly[] GetModuleAssemblies()
        {
            // attempt to load all assemblies in the "hosts" sub-directory
            var uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var hostsPath = Path.GetDirectoryName(uri.LocalPath);
            hostsPath = Path.Combine(hostsPath, "hosts");

            var hostAssemblies = new List<Assembly>();

            foreach (var file in Directory.GetFiles(hostsPath))
            {
                if (string.Compare(Path.GetExtension(file), ".dll", true) == 0)
                {
                    try
                    {
                        hostAssemblies.Add(Assembly.LoadFrom(file));
                    }
                    catch
                    {
                        Debug.WriteLine("Error loading assembly: " + Path.GetFileName(file));
                    }
                }
            }

            return hostAssemblies.ToArray();
        }

        public string GetModuleListXml()
        {
            //// attempt to load all assemblies in the "hosts" sub-directory
            //var uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
            //var hostsPath = Path.GetDirectoryName(uri.LocalPath);
            //hostsPath = Path.Combine(hostsPath, "hosts");

            //var modulesNode = new XElement("Modules");

            //foreach (var file in Directory.GetFiles(hostsPath))
            //{
            //    if(string.Compare(Path.GetExtension(file), ".dll", true) == 0)
            //    modulesNode.Add(file);
            //}

            //var doc = new XDocument(
            //    new XDeclaration("1.0", "utf-8", "yes"),
            //    new XElement("SolutionProfile",
            //        modulesNode));

            //return doc.Declaration + doc.ToString();
            return null;
        }
    }
}
